package com.hserver.deploy.controller;

import com.hserver.deploy.bean.JavaDeploy;
import com.hserver.deploy.service.IndexService;
import top.hserver.core.event.HServerEvent;
import top.hserver.core.interfaces.HttpRequest;
import top.hserver.core.interfaces.HttpResponse;
import top.hserver.core.ioc.annotation.Autowired;
import top.hserver.core.ioc.annotation.Controller;
import top.hserver.core.ioc.annotation.RequestMapping;
import top.hserver.core.ioc.annotation.RequestMethod;
import top.hserver.core.server.util.JsonResult;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 线上环境的后台服务自动化部署
 */
@Controller("/javadeploy/")
public class JavaDeployController {

    @Autowired
    private IndexService javaDeployService;

    /**
     * 添加项目页面
     */
    @RequestMapping(value = "new", method = RequestMethod.GET)
    public void newService(HttpResponse response) {
        response.sendTemplate("javadeploy/new.ftl", new HashMap<>());
    }

    /**
     * 添加项目请求
     */
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public void insert(JavaDeploy javaDeployInfo, HttpResponse response) {
        String uuid = UUID.randomUUID().toString();
        javaDeployInfo.setUuid(uuid);
        javaDeployService.insert(javaDeployInfo);
        response.redirect("/javadeploy/detail/" + uuid);
    }

    /**
     * 详情页面
     */
    @RequestMapping(value = "detail/{uuid}", method = RequestMethod.GET)
    public void detail(HttpRequest request, HttpResponse response) {
        Map<String, Object> data = new HashMap<>();
        data.put("detail", javaDeployService.getDetail(request.query("uuid")));
        response.sendTemplate("javadeploy/detail.ftl", data);
    }

    @RequestMapping(value = "del/{uuid}", method = RequestMethod.GET)
    public void del(HttpRequest request, HttpResponse response) {
        javaDeployService.del(request.query("uuid"));
        response.redirect("/");
    }

    /**
     * ajax查看运行状态
     */
    @RequestMapping(value = "status", method = RequestMethod.POST)
    public String ajaxStatus(String uuid) throws IOException {
        return javaDeployService.getStatus(uuid);
    }

    /**
     * ajax部署
     */
    @RequestMapping(value = "deploy", method = {RequestMethod.POST,RequestMethod.GET})
    public JsonResult ajaxDeploy(String uuid) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        HServerEvent.sendEvent("/deploy", map);
        return JsonResult.ok();
    }

    /**
     * ajax重启
     */
    @RequestMapping(value = "restart", method = RequestMethod.POST)
    public String ajaxRestart(String uuid) throws IOException {
        return javaDeployService.restart(uuid);
    }

    /**
     * ajax停止
     */
    @RequestMapping(value = "stop", method = RequestMethod.POST)
    public String ajaxStop(String uuid) throws IOException {
        return javaDeployService.stop(uuid);
    }

}
